import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { addNumberAction, subNumberAction } from '../store/counter'

export class Counter extends PureComponent {
  calcNumber(number, isAdd) {
    if (isAdd) {
      this.props.addNumber(number)
    } else {
      this.props.subNumber(number)
    }
  }
  
  render() {
    const { counter } = this.props
    
    return (
      <div>
        <h3>Counter redux</h3>
        <p>当前计数: {counter}</p>
        <button onClick={e => this.calcNumber(6, true)}>+6</button>
        <button onClick={e => this.calcNumber(88, true)}>+88</button>
        <button onClick={e => this.calcNumber(6, false)}>-6</button>
        <button onClick={e => this.calcNumber(88, false)}>-88</button>
      </div>
    )
  }
}

// mapStateToProps: 把store中的状态映射到组件的props中
const mapStateToProps = (state) => ({
  counter: state.counter.counter
})

// mapDispatchToProps: 把store中的dispatch映射到组件的props中
const mapDispatchToProps = (dispatch) => ({
  addNumber: (number) => dispatch(addNumberAction(number)),
  subNumber: (number) => dispatch(subNumberAction(number))
})

export default connect(mapStateToProps, mapDispatchToProps)(Counter)
